package com.spring.mybatis.core;

import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author yangjian
 */
@Component
public class MybatisMapperFactoryMethod {

	// 获取 Mapper 工厂方法
	public static <T> T getMapper(Class<T> mapperInterface)
	{
		return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[]{mapperInterface}, new InvocationHandler() {
			@Override
			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
			{
				// 这里还可以处理 @Select 注解，可以直接把 SQL 语句送到 JDBC 执行，不走 Mybatis
				if (method.isAnnotationPresent(Select.class)) {
					Select annotation = method.getAnnotation(Select.class);
					String sql = annotation.value()[0];
					System.out.println("SQL: " + sql);
				}
				return null;
			}
		});
	}
}
